package com.aneliya.proxy;

import java.util.ArrayList;
import java.util.Hashtable;

import com.aneliya.command.chatWindow.UpdateOnlineUsersCommand;
import com.aneliya.framework.mvc.Facade;
import com.aneliya.framework.mvc.controller.MVCEvent;
import com.aneliya.framework.mvc.model.Proxy;

public class OnlineUsersProxy extends Proxy {
	public static final String UPDATE_ONLINE_USERS_EVENT = "updateOnlineUsers";
	
	private Hashtable<String, Boolean> usersOnline;
	
	public ArrayList<String> getOnlineUsers() {
		ArrayList<String> result = new ArrayList<String>();
		for (String username : usersOnline.keySet()) {
			if (usersOnline.get(username)) {
				result.add(username);
			}
		}
		return result;
	}

	public OnlineUsersProxy() throws Exception {
		name = "OnlineUsersProxy";
		facade = Facade.getInstance();
		
		usersOnline = new Hashtable<String, Boolean>();
		
		initializeCommands();
	}
	
	private void initializeCommands() throws Exception {
		facade.registerCommand(UPDATE_ONLINE_USERS_EVENT, UpdateOnlineUsersCommand.class);
	}
	
	public void addOnlineUser(String username) throws InstantiationException, IllegalAccessException {
		usersOnline.put(username, true);
		facade.dispatchMVCEvent(new MVCEvent(this, UPDATE_ONLINE_USERS_EVENT, null));
	}
	
	public void removeOnlineUser(String username) throws InstantiationException, IllegalAccessException {
		usersOnline.put(username, false);
		facade.dispatchMVCEvent(new MVCEvent(this, UPDATE_ONLINE_USERS_EVENT, null));
	}

}
